package net.mingsoft.examine.utils;

import com.alibaba.fastjson.JSONObject;
import net.mingsoft.examine.enums.QueryTimeTypeEnum;
import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DateUtil {
    // 格式：年－月－日 小时：分钟：秒
    public static final String FORMAT_ONE = "yyyy-MM-dd HH:mm:ss";

    // 格式：年－月－日 小时：分钟
    public static final String FORMAT_TWO = "yyyy-MM-dd HH:mm";

    // 格式：年月日 小时分钟秒
    public static final String FORMAT_THREE = "yyyyMMdd-HHmmss";

    public static final String FORMAT_FOUR = "yyyyMMddHHmmss";

    // 格式： 年月日 小时分钟秒
    public static final String FORMAT_FIVE = "yyyy-MM-dd HH:mm:ss";

    public static final String FORMAT_SIX = "yyyy-MM-dd HH";

    public static final String FORMATE_EIGHT = "yyyyMMdd";

    // 格式：年－月－日
    public static final String LONG_DATE_FORMAT = "yyyy-MM-dd";

    // 格式：XXXX年XX月XX日
    public static final String CHINA_DATE_FORMAT = "yyyy年MM月dd日";

    // 格式：月－日
    public static final String SHORT_DATE_FORMAT = "MM-dd";

    // 格式：小时：分钟：秒
    public static final String LONG_TIME_FORMAT = "HH:mm:ss";

    // 格式：年-月
    public static final String MONTG_DATE_FORMAT = "yyyy-MM";

    public static final String FILE_DATE_DIR_FORMAT = "yyyyMMdd";

    public static final String YEAR_DATE_FORMAT = "yyyy";

    // 格式：小时
    public static final String HOUR_TIME_FORMAT = "HH";

    // 年的加减
    public static final int SUB_YEAR = Calendar.YEAR;

    // 月加减
    public static final int SUB_MONTH = Calendar.MONTH;

    // 天的加减
    public static final int SUB_DAY = Calendar.DATE;

    // 小时的加减
    public static final int SUB_HOUR = Calendar.HOUR;

    // 分钟的加减
    public static final int SUB_MINUTE = Calendar.MINUTE;

    // 秒的加减
    public static final int SUB_SECOND = Calendar.SECOND;

    public static final int HOUR_OF_DAY = Calendar.HOUR_OF_DAY;

    static final String dayNames[] = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};

    @SuppressWarnings("unused")
    public static final SimpleDateFormat timeFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static final SimpleDateFormat timeFormat2 = new SimpleDateFormat("yyyy-MM-dd");
    public static final SimpleDateFormat timeFormat3 = new SimpleDateFormat("yyyy-MM");
    public static final SimpleDateFormat timeFormat4 = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    public DateUtil() {
    }

    public static String format1(Date date){
        return timeFormat1.format(date);
    }

    public static String format2(Date date){
        return timeFormat2.format(date);
    }

    public static String format3(Date date){
        return timeFormat3.format(date);
    }

    public static String format4(Date date){
        return timeFormat4.format(date);
    }

    public static Date parse(String time) throws ParseException {
        return timeFormat1.parse(time);
    }

    public static final DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    public static String localDateTimeToString(LocalDateTime localDateTime){
        return df.format(localDateTime);
    }

    /**
     * 把符合日期格式的字符串转换为日期类型
     *
     * @param dateStr
     * @return
     */
    public static LocalDateTime stringtoDate(String dateStr) {
        return  LocalDateTime.parse(dateStr, df);
    }

    /**
     * 把符合日期格式的字符串转换为日期类型
     *
     * @param dateStr
     * @return
     */
    public static Date stringtoDate(String dateStr, String format) {
        Date d = null;
        if (null == dateStr || dateStr.isEmpty()) {
            return d;
        }
        SimpleDateFormat formater = new SimpleDateFormat(format);
        try {
            formater.setLenient(false);
            d = formater.parse(dateStr);
        } catch (Exception e) {
            // logger.error ( e );
            d = null;
        }
        return d;
    }


    /**
     * 把符合日期格式的字符串转换为日期类型
     */
    public static Date stringtoDate(String dateStr, String format, ParsePosition pos) {
        Date d = null;
        SimpleDateFormat formater = new SimpleDateFormat(format);
        try {
            formater.setLenient(false);
            d = formater.parse(dateStr, pos);
        } catch (Exception e) {
            // logger.error ( e );
            d = null;
        }
        return d;
    }

    /**
     * 把日期转换为字符串
     *
     * @param date
     * @return
     */
    public static String dateToString(Date date, String format) {
        String result = "";
        SimpleDateFormat formater = new SimpleDateFormat(format);
        try {
            result = formater.format(date);
        } catch (Exception e) {
            // logger.error ( e );
        }
        return result;
    }


    /**
     * @Type:method
     * @describe：把日期加上某个日期（单位：天）再转换为字符串
     * @Parameter:
     * @Return:
     * @Date:2019/4/1
     */
    public static String dateChangeToString(Date date, int day, String format) {
        String result = "";
        SimpleDateFormat formater = new SimpleDateFormat(format);

        //修改时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, day);
        date = calendar.getTime();

        try {
            result = formater.format(date);
        } catch (Exception e) {
            // logger.error ( e );
        }
        return result;
    }


    /**
     * 获取当前时间的指定格式
     *
     * @param format
     * @return
     */
    public static String getCurrDate(String format) {
        return dateToString(new Date(), format);
    }

    /**
     * 两个日期相加
     *
     * @param dateStr
     * @param amount
     * @return
     */
    public static String dateSub(int dateKind, String dateStr, int amount) {
        Date date = stringtoDate(dateStr, FORMAT_ONE);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(dateKind, amount);
        return dateToString(calendar.getTime(), FORMAT_ONE);
    }

    /**
     * 两个日期相减
     *
     * @param firstTime
     * @param secTime
     * @return 相减得到的秒数
     */
    public static long timeSub(String firstTime, String secTime) {
        long first = stringtoDate(firstTime, FORMAT_ONE).getTime();
        long second = stringtoDate(secTime, FORMAT_ONE).getTime();
        return (second - first) / 1000;
    }

    /**
     * 获得某月的天数
     *
     * @param year  int
     * @param month int
     * @return int
     */
    public static int getDaysOfMonth(String year, String month) {
        int days = 0;
        if (month.equals("1") || month.equals("3") || month.equals("5") || month.equals("7") || month.equals("8")
                || month.equals("10") || month.equals("12")) {
            days = 31;
        } else if (month.equals("4") || month.equals("6") || month.equals("9") || month.equals("11")) {
            days = 30;
        } else {
            if ((Integer.parseInt(year) % 4 == 0 && Integer.parseInt(year) % 100 != 0)
                    || Integer.parseInt(year) % 400 == 0) {
                days = 29;
            } else {
                days = 28;
            }
        }

        return days;
    }

    /**
     * 获取某年某月的天数
     *
     * @param year  int
     * @param month int 月份[1-12]
     * @return int
     */
    public static int getDaysOfMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 1);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获得当前日期
     *
     * @return int
     */
    public static int getToday() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.DATE);
    }

    /**
     * 获得当前月份
     *
     * @return int
     */
    public static int getToMonth() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.MONTH) + 1;
    }

    /**
     * 获得当前年份
     *
     * @return int
     */
    public static int getToYear() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR);
    }

    /**
     * 返回日期的天
     *
     * @param date Date
     * @return int
     */
    public static int getDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.DATE);
    }

    /**
     * 返回日期的年
     *
     * @param date Date
     * @return int
     */
    public static int getYear(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.YEAR);
    }

    /**
     * 返回日期的月份，1-12
     *
     * @param date Date
     * @return int
     */
    public static int getMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH) + 1;
    }

    /**
     * 比较两个日期的年差
     *
     * @param before
     * @param after
     * @return
     */
    public static int yearDiff(String before, String after) {
        Date beforeDay = stringtoDate(before, LONG_DATE_FORMAT);
        Date afterDay = stringtoDate(after, LONG_DATE_FORMAT);
        return getYear(afterDay) - getYear(beforeDay);
    }

    /**
     * 比较指定日期与当前日期的差
     *
     * @param after
     * @param after
     * @return
     */
    public static int yearDiffCurr(String after) {
        Date beforeDay = new Date();
        Date afterDay = stringtoDate(after, LONG_DATE_FORMAT);
        return getYear(beforeDay) - getYear(afterDay);
    }

    /**
     * 比较指定日期与当前日期的差
     *
     * @param before
     * @return
     * @author chenyz
     */
    public static long dayDiffCurr(String before) {
        Date currDate = DateUtil.stringtoDate(currDay(), LONG_DATE_FORMAT);
        Date beforeDate = stringtoDate(before, LONG_DATE_FORMAT);
        return (currDate.getTime() - beforeDate.getTime()) / 86400000;

    }

    /**
     * 比较指定日期与当前日期的差
     *
     * @param before
     * @return
     * @author chenyz
     */
    public static int dayDiff(String before, String after) {
        Date afterDate = stringtoDate(after, LONG_DATE_FORMAT);
        Date beforeDate = stringtoDate(before, LONG_DATE_FORMAT);
        long day = (afterDate.getTime() - beforeDate.getTime()) / 86400000;
        Integer integer = Integer.valueOf(String.valueOf(day));
        return integer;

    }

    /**
     * 获取每月的第一周
     *
     * @param year
     * @param month
     * @return
     * @author chenyz
     */
    public static int getFirstWeekdayOfMonth(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.setFirstDayOfWeek(Calendar.SATURDAY); // 星期天为第一天
        c.set(year, month - 1, 1);
        return c.get(Calendar.DAY_OF_WEEK);
    }

    /**
     * 获取每月的最后一周
     *
     * @param year
     * @param month
     * @return
     * @author chenyz
     */
    public static int getLastWeekdayOfMonth(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.setFirstDayOfWeek(Calendar.SATURDAY); // 星期天为第一天
        c.set(year, month - 1, getDaysOfMonth(year, month));
        return c.get(Calendar.DAY_OF_WEEK);
    }

    /**
     * 获得当前日期字符串，格式"yyyy-MM-dd HH:mm:ss"
     *
     * @return
     */
    public static String getNow() {
        Calendar today = Calendar.getInstance();
        return dateToString(today.getTime(), FORMAT_ONE);
    }

    /**
     * 根据生日获取星座
     *
     * @param birth YYYY-mm-dd
     * @return
     */
    public static String getAstro(String birth) {
        if (!isDate(birth)) {
            birth = "2000" + birth;
        }
        if (!isDate(birth)) {
            return "";
        }
        int month = Integer.parseInt(birth.substring(birth.indexOf("-") + 1, birth.lastIndexOf("-")));
        int day = Integer.parseInt(birth.substring(birth.lastIndexOf("-") + 1));
        String s = "魔羯水瓶双鱼牡羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
        int[] arr = {20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22};
        int start = month * 2 - (day < arr[month - 1] ? 2 : 0);
        return s.substring(start, start + 2) + "座";
    }

    /**
     * 判断日期是否有效,包括闰年的情况
     *
     * @param date YYYY-mm-dd
     * @return
     */
    public static boolean isDate(String date) {
        StringBuffer reg = new StringBuffer("^((\\d{2}(([02468][048])|([13579][26]))-?((((0?");
        reg.append("[13578])|(1[02]))-?((0?[1-9])|([1-2][0-9])|(3[01])))");
        reg.append("|(((0?[469])|(11))-?((0?[1-9])|([1-2][0-9])|(30)))|");
        reg.append("(0?2-?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][12");
        reg.append("35679])|([13579][01345789]))-?((((0?[13578])|(1[02]))");
        reg.append("-?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))");
        reg.append("-?((0?[1-9])|([1-2][0-9])|(30)))|(0?2-?((0?[");
        reg.append("1-9])|(1[0-9])|(2[0-8]))))))");
        Pattern p = Pattern.compile(reg.toString());
        return p.matcher(date).matches();
    }

    /**
     * 取得指定日期过 months 月后的日期 (当 months 为负数表示指定月之前);
     *
     * @param date   日期 为null时表示当天
     * @param months 相加(相减)的月数
     */
    public static Date nextMonth(Date date, int months) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        cal.add(Calendar.MONTH, months);
        return cal.getTime();
    }

    /**
     * 取得指定日期过 day 天后的日期 (当 day 为负数表示指日期之前);
     *
     * @param date 日期 为null时表示当天
     * @param day  相加(相减)的月数
     */
    public static Date nextDay(Date date, int day) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        cal.add(Calendar.DAY_OF_YEAR, day);
        return cal.getTime();
    }

    /**
     * 取得距离今天 day 日的日期
     *
     * @param day
     * @param format
     * @return
     * @author chenyz
     */
    public static String nextDay(int day, String format) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DAY_OF_YEAR, day);
        return dateToString(cal.getTime(), format);
    }


    /**
     * 取上N个月,或者下N个月
     *
     * @param date
     * @param step
     * @return
     */
    public static long getSomeMonth(Date date, int step) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        } else {
            cal.setTime(new Date());
        }
        cal.add(Calendar.MONTH, step);

        long time = cal.getTime().getTime();
        return time;
    }


    /**
     * 取得指定日期过 day 周后的日期 (当 day 为负数表示指定月之前)
     *
     * @param date 日期 为null时表示当天
     */
    public static Date nextWeek(Date date, int week) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        cal.add(Calendar.WEEK_OF_MONTH, week);
        return cal.getTime();
    }

    public static Date nextHour(Date date, int hour) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        cal.add(Calendar.HOUR_OF_DAY, hour);
        return cal.getTime();
    }

    public static Date nextMinute(Date date, int minute) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        cal.add(Calendar.MINUTE, minute);
        return cal.getTime();
    }

    public static Date nextSecond(Date date, int second) {
        Calendar cal = Calendar.getInstance();
        if (date != null) {
            cal.setTime(date);
        }
        cal.add(Calendar.SECOND, second);
        return cal.getTime();
    }

    /**
     * 获取当前的日期(yyyy-MM-dd)
     */
    public static String currDay() {
        return DateUtil.dateToString(new Date(), DateUtil.LONG_DATE_FORMAT);
    }

    /**
     * 获取昨天的日期
     *
     * @return
     */
    public static String befoDay() {
        return befoDay(DateUtil.LONG_DATE_FORMAT);
    }

    /**
     * 根据时间类型获取昨天的日期
     *
     * @param format
     * @return
     * @author chenyz
     */
    public static String befoDay(String format) {
        return DateUtil.dateToString(DateUtil.nextDay(new Date(), -1), format);
    }

    /**
     * 获取明天的日期
     */
    public static String afterDay() {
        return DateUtil.dateToString(DateUtil.nextDay(new Date(), 1), DateUtil.LONG_DATE_FORMAT);
    }

    /**
     * 取得当前时间距离1900/1/1的天数
     *
     * @return
     */
    public static int getDayNum() {
        int daynum = 0;
        GregorianCalendar gd = new GregorianCalendar();
        Date dt = gd.getTime();
        GregorianCalendar gd1 = new GregorianCalendar(1900, 1, 1);
        Date dt1 = gd1.getTime();
        daynum = (int) ((dt.getTime() - dt1.getTime()) / (24 * 60 * 60 * 1000));
        return daynum;
    }

    /**
     * getDayNum的逆方法(用于处理Excel取出的日期格式数据等)
     *
     * @param day
     * @return
     */
    public static Date getDateByNum(int day) {
        GregorianCalendar gd = new GregorianCalendar(1900, 1, 1);
        Date date = gd.getTime();
        date = nextDay(date, day);
        return date;
    }

    /**
     * 针对yyyy-MM-dd HH:mm:ss格式,显示yyyymmdd
     */
    public static String getYmdDateCN(String datestr) {
        if (datestr == null)
            return "";
        if (datestr.length() < 10)
            return "";
        StringBuffer buf = new StringBuffer();
        buf.append(datestr.substring(0, 4)).append(datestr.substring(5, 7)).append(datestr.substring(8, 10));
        return buf.toString();
    }

    /**
     * 获取本月第一天
     *
     * @param format
     * @return
     */
    public static String getFirstDayOfMonth(String format) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DATE, 1);
        return dateToString(cal.getTime(), format);
    }

    /**
     * 获取本月最后一天
     *
     * @param format
     * @return
     */
    public static String getLastDayOfMonth(String format) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DATE, 1);
        cal.add(Calendar.MONTH, 1);
        cal.add(Calendar.DATE, -1);
        return dateToString(cal.getTime(), format);
    }

    /**
     * 获取某一个field之前指定时长的时间
     *
     * @param getField
     * @param destField
     * @param before
     * @return
     */
    public static int getFieldBeforeNow(int getField, int destField, int before) {
        Calendar cal = Calendar.getInstance();
        cal.add(destField, -before);
        return cal.get(getField);
    }

    public static Date getDateBeforeNow(int destField, int before) {
        Calendar cal = Calendar.getInstance();
        cal.add(destField, -before);
        return cal.getTime();
    }

    public static Date getDateBeforeNow(int destField, int before, Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(destField, -before);
        return cal.getTime();
    }

    public static Date startHour() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        return cal.getTime();
    }

    public static Long getSequence() {
        String detestr = System.currentTimeMillis() + "";
        Random random = new Random();
        int n = random.nextInt(1000);
        while ((n + "").length() < 3) {
            n = random.nextInt(1000);
        }
        String result = detestr + n;
        Long dateLong = Long.valueOf(result);
        // System.out.println(dateLong+":"+n);
        return dateLong;
    }

    /**
     * 获取当前时间前一天的开始和结束时间
     */
    public static String beforeOneDayToNowDate(String formate) {
        Map<String, String> params = new HashMap<String, String>();
        Date nowDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(nowDate);
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        return DateUtil.dateToString(calendar.getTime(), formate);
    }

    public static String getSpecifiedDayBefore(String specifiedDay) {
        // SimpleDateFormat simpleDateFormat = new
        // SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        Date date = null;
        try {
            date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day - 1);

        String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        return dayBefore;
    }

    /**
     * @Title: getTimeByIndicate @Description:
     * 根据传入的时间、单位、间隔、个数、格式获得时间列表(T为String 或Date类型) e.g List<String>
     * list=getTimeByIndicate("2016-12-12 13:00:00", Calendar.HOUR_OF_DAY,
     * 24,12, "yyyy-MM-dd HH:00:00"); @return List<String> @throws
     */
    public static <T> List<String> getTimeByIndicate(T date, int CalendarUnit, int interval, int count, String fmt) {
        List<String> times = new ArrayList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat(fmt);
        sdf.setLenient(false);
        Date time = new Date();
        Pattern p = Pattern.compile("^\\d{4}\\D+\\d{2}\\D+\\d{2}$");
        try {
            if (date instanceof String) {
                String str = date.toString().trim();
                Matcher m = p.matcher(str);
                if (m.matches()) {
                    time = sdf.parse(str + " 00:00:00");
                } else {
                    time = sdf.parse(str);
                }

            } else {
                String fmt_time = sdf.format(date);
                time = sdf.parse(fmt_time);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < count; i++) {
            Calendar cal = Calendar.getInstance();
            if (date != null) {
                cal.setTime(time);
            }
            cal.add(CalendarUnit, i * interval);
            times.add(sdf.format(cal.getTime()));
        }
        return times;
    }

    /**
     * @Title: getFiveMinPointBeforeNow @Description:
     * 获取距离给定时间之前的最大的整5分钟时间点 @param date @return String   @throws
     */
    public static String getFiveMinPointBeforeNow(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Pattern time_pattern = Pattern
                .compile("\\b(^\\d{4}\\D+\\d{2}\\D+\\d{2}\\s\\d{2}\\D+[0-5])([0-9])\\D+\\d{2}$\\b");
        Pattern min_pattern = Pattern.compile("^[0-4]$");
        String time_str = sdf.format(date);
        Matcher matcher = time_pattern.matcher(time_str);
        String prefix = matcher.replaceAll("$1");
        String min_str = matcher.replaceAll("$2");
        matcher = min_pattern.matcher(min_str);
        if (matcher.matches()) {
            time_str = prefix + "0:00";
        } else {
            time_str = prefix + "5:00";
        }
        return time_str;
    }

    /**
     * @description str转换为long（秒级）
     * @author hjb
     * @date2017年12月22日 下午3:10:58
     */
    public static long str2Long(SimpleDateFormat sdf, String str) {
        long time = 0l;
        try {
            time = sdf.parse(str).getTime() / 1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    /**
     * @description 传入的日期与当前日期比较 传入的日期格式yyyy-MM-dd
     * @author mj
     * @date2018年04月20日 下午3:10:58
     * @ return 1:当前时间大于传入时间 0:两个时间相等 -1:当前时间小于传入时间
     */
    public static int nowDateReduce(String str) {
        int i = 0;
        try {
            if (str != null && !"".equals(str)) {
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String dateStr = sdf.format(date);
                Date dateNow = sdf.parse(dateStr);
                Date parseDate = sdf.parse(str);
                i = dateNow.compareTo(parseDate);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return i;
    }

    /**
     * @description 传入的两个日期进行比较 传入的日期格式yyyy-MM-dd
     * @author mj
     * @date2018年04月20日 下午3:10:58
     * @ return 1:有效时间大于绿色通道时间 0两个时间相等 -1:有效时间小于绿色通道时间
     */
    public static int twoDateReduce(String expiryDate, String greenDate) {
        int i = 0;
        try {
            if (expiryDate != null && !"".equals(expiryDate) && greenDate != null && !"".equals(greenDate)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date parseExpiryDate = sdf.parse(expiryDate);
                Date parseGreenDate = sdf.parse(greenDate);
                i = parseExpiryDate.compareTo(parseGreenDate);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return i;
    }


    /**
     * @description 传入的日期加上指定的天数
     * @author mj
     * @date2017年12月22日 下午3:10:58
     * @ return
     */
    public static String dateAddDay(String date, int day) {
        String end = "";
        try {
            if (date != null && !"".equals(date)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Date parseDate = sdf.parse(date);
                Calendar ca = Calendar.getInstance();
                ca.setTime(parseDate);
                ca.add(Calendar.DATE, day);
                parseDate = ca.getTime();
                end = sdf.format(parseDate);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return end;
    }

    /**
     * 传入的日期加上指定的天数
     * @param date 时间
     * @param day 添加天数
     * @param format 时间格式
     * @return
     */
    public static String dateAddDayV2(String date, int day, String format) {
        String end = "";
        try {
            if (date != null && !"".equals(date)) {
                SimpleDateFormat sdf = new SimpleDateFormat(format);
                Date parseDate = sdf.parse(date);
                Calendar ca = Calendar.getInstance();
                ca.setTime(parseDate);
                ca.add(Calendar.DATE, day);
                parseDate = ca.getTime();
                end = sdf.format(parseDate);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return end;
    }

    public static long specifyDay(int day) {
        Date date = stringtoDate(getCurrDate("yyyy-MM-dd 00:00:00"), "yyyy-MM-dd 00:00:00");
        Calendar cal = Calendar.getInstance();

        if (date != null) {
            cal.setTime(date);
        }
        cal.add(Calendar.DAY_OF_YEAR, day);
        return cal.getTimeInMillis() / 1000;
    }

    /**
     * @Type:method
     * @describe：此方法用于：判断当前时间是否等于另外一个时间加上某个时间段（只精确到天）
     * @Parameter: currentDate, timeSlot，otherDate,
     * @Return: false 或者 true
     * @Date:2019/4/1
     */
    public static Boolean currentDateEqualOtherDate(Date currentDate, int timeSlot, Date otherDate) {

        String currentDateStr = DateUtil.dateToString(currentDate, DateUtil.LONG_DATE_FORMAT);
        String otherDateStr = DateUtil.dateChangeToString(otherDate, timeSlot, DateUtil.LONG_DATE_FORMAT);

        if (currentDateStr.equals(otherDateStr)) {
            return true;
        } else {
            return false;
        }

    }

    /*
     * 将时间戳转换为时间
     */
    public static Date stampToDate(String s) {
        long lt = new Long(s);
        Date date = new Date(lt);
        return date;
    }

    //根据秒数获取时间 格式：xx时x分
    public static String getDuration (String time){
        Scanner input = new Scanner(time);
        int second = input.nextInt();

        final StringBuilder ret = new StringBuilder();

        int day = second / 86400;
        if (day > 0) {
            second = second % 86400;
            ret.append(day);
            ret.append("天");
        }

        int hour = second / 3600;
        if (hour > 0) {
            second = second % 3600;
            ret.append(hour);
            ret.append("时");
        }

        int minute = second / 60;
        if (minute > 0) {
            second = second % 60;
            ret.append(minute);
            ret.append("分");
        }

        if (second > 0) {
            ret.append(second);
            ret.append("秒");
        }

        return ret.toString();
    } // getDuration()

    //根据秒数获取时间 格式：xx分xx秒
    public static String getCellTime (String time){
        Scanner input = new Scanner(time);
        int hour,minute,second;
        second = input.nextInt();
        hour = second/3600;
        minute = (second - hour*3600)/60;
        second = second-hour*300-minute*60;
        return minute+"分"+second+"秒";

    }

    /**
     * 获取某月的天数
     * @param date 月份 例如：2018-12
     * @return
     */
    public static String getMonthDays(String date){
        String day = "";
        int year = Integer.parseInt(date.substring(0,4));
        int month = Integer.parseInt(date.substring(5,7));;
        Calendar c = Calendar.getInstance();
        c.set(year, month, 0); //输入类型为int类型

        int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
        if(dayOfMonth < 10){
            day = "0"+dayOfMonth;
        }else{
            day = String.valueOf(dayOfMonth);
        }

        return day;
    }


    /**
     * 获取年龄
     * @param birthday
     * @return
     */
    public static int getAgeByBirth(Date birthday) {
        int age = 0;
        try {
            Calendar now = Calendar.getInstance();
            now.setTime(new Date());// 当前时间

            Calendar birth = Calendar.getInstance();
            birth.setTime(birthday);

            if (birth.after(now)) {//如果传入的时间，在当前时间的后面，返回0岁
                age = 0;
            } else {
                age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
                if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
                    age += 1;
                }
            }
            return age;
        } catch (Exception e) {//兼容性更强,异常后返回数据
            return 0;
        }
    }

    /**
     * 比较两个日期的大小
     * @param firstTime 第一个时间
     * @param secTime   第二个时间
     * @param format    时间格式
     * @return 0：firstTime=secTime，负数：firstTime>secTime，正数：firstTime<secTime
     */
    public static long timeCompare(String firstTime, String secTime, String format) {
            long first = stringtoDate(firstTime, format).getTime();
            long second = stringtoDate(secTime, format).getTime();
            return (second - first) / 1000;
    }

    /**
     * 查询时间范围 1：昨天 2：今天 3：近三天 4：近七天 5：近一个月 6：近一个季度 7：近一年
     * @param queryTimeType
     * @return
     */
    public static String getQueryTime(Integer queryTimeType) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        String date = "";
        if(QueryTimeTypeEnum.YESTERDAY.getCode().equals(queryTimeType)){
            //昨天
            c.setTime(new Date());
            c.add(Calendar.DATE, - 1);
            Date d = c.getTime();
            date = format.format(d);
        }else if(QueryTimeTypeEnum.TODAY.getCode().equals(queryTimeType)){
            //今天
            c.setTime(new Date());
            c.add(Calendar.DATE, 0);
            Date d = c.getTime();
            date = format.format(d);
        }else if(QueryTimeTypeEnum.THREE_MONTH.getCode().equals(queryTimeType)){
            //过去三天
            c.setTime(new Date());
            c.add(Calendar.DATE, - 3);
            Date d = c.getTime();
            date = format.format(d);
        }else if(QueryTimeTypeEnum.SEVEN_DAY.getCode().equals(queryTimeType)){
            //过去七天
            c.setTime(new Date());
            c.add(Calendar.DATE, - 7);
            Date d = c.getTime();
            date = format.format(d);
        }else if(QueryTimeTypeEnum.ONE_MONTH.getCode().equals(queryTimeType)){
            //过去一月
            c.setTime(new Date());
            c.add(Calendar.MONTH, -1);
            Date m = c.getTime();
            date = format.format(m);
        }else if(QueryTimeTypeEnum.ONE_QUARTERLY.getCode().equals(queryTimeType)){
            //过去三个月
            c.setTime(new Date());
            c.add(Calendar.MONTH, -3);
            Date m3 = c.getTime();
            date = format.format(m3);
        }else if(QueryTimeTypeEnum.ONE_YEAR.getCode().equals(queryTimeType)){
            //过去一年
            c.setTime(new Date());
            c.add(Calendar.YEAR, -1);
            Date y = c.getTime();
            date = format.format(y);
        }
        return date;
    }

    /**
     * 获取相差的时间
     * @param currentDate 当前时间
     * @param field 计算的方式：Calendar.WEEK_OF_MONTH
     * @param amount 计算数量
     * @return 新的时间
     */
    public static Date calendarAdd(Date currentDate, int field, int amount){
        Calendar calendar = Calendar.getInstance(Locale.CHINESE);
        calendar.setTime(currentDate);
        calendar.add(field, amount);
        return calendar.getTime();
    }

    // 计算2个时间相差的天数
    public static long dayDiff(Date startTime, Date endTime){
        try {
            long diff = endTime.getTime() - startTime.getTime();
            // 一天的毫秒数
            long nd = 1000 * 24 * 60 * 60;
            return diff / nd;
        } catch (Exception e) {
            return -1;
        }
    }

    /**
     * 获取过去7天内的日期数组
     * @param intervals      intervals天内
     * @return              日期数组
     */
    public static List<String> getDays(int intervals) {
        List<String> pastDaysList = new ArrayList<>();
        for (int i = intervals -1; i >= 0; i--) {
            pastDaysList.add(getPastDate(i));
        }
        return pastDaysList;
    }
    /**
     * 获取过去第几天的日期
     * @param past 天数
     * @return
     */
    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("MM/dd");
        String result = format.format(today);
        return result;
    }

    /**
     * 获取过去第几天的日期
     * @param date  日期
     * @param past  天数
     * @return
     */
    public static String getPastDate(Date date, int past) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DATE, past);
        Date d = c.getTime();
        String day = format.format(d);
        return day;
    }

    /**
     *  获取某年某月 所有日期（yyyy-mm-dd格式字符串）
     * @param year
     * @param month
     * @return
     */
    public static List<String> getMonthFullDay(int year , int month){
        SimpleDateFormat dateFormatYYYYMMDD = new SimpleDateFormat("yyyy-MM-dd");
        List<String> fullDayList = new ArrayList<>();
        // 获得当前日期对象
        Calendar cal = Calendar.getInstance();
        cal.clear();// 清除信息
        cal.set(Calendar.YEAR, year);
        // 1月从0开始
        cal.set(Calendar.MONTH, month-1);
        // 当月1号
        cal.set(Calendar.DAY_OF_MONTH,1);
        int count = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        for (int j = 1; j <= count ; j++) {
            fullDayList.add(dateFormatYYYYMMDD.format(cal.getTime()));
            cal.add(Calendar.DAY_OF_MONTH,1);
        }
        return fullDayList;
    }

    /**
     *  某年某月的最后一天
     * @param year
     * @param month
     * @return
     */
    public static String getLastDay(int year,int month){
        SimpleDateFormat dateFormatYYYYMMDD = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH, 0);
        return dateFormatYYYYMMDD.format(cal.getTime());
    }

    public static List<String> getMonthBetween(String minDate, String maxDate) {
        ArrayList<String> result = new ArrayList<String>();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月

            Calendar min = Calendar.getInstance();
            Calendar max = Calendar.getInstance();

            min.setTime(sdf.parse(minDate));
            min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

            max.setTime(sdf.parse(maxDate));
            max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

            Calendar curr = min;
            while (curr.before(max)) {
                result.add(sdf.format(curr.getTime()));
                curr.add(Calendar.MONTH, 1);
            }
        } catch (Exception e) {
        }
        return result;
    }

    /**
     * 计算结束日期
     * @param startTime 开始日期，格式：yyyy-MM-dd
     * @param day   天数
     * @return
     */
    public static String getEndTime(String startTime, int day) throws ParseException {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(timeFormat2.parse(startTime));
        calendar.add(Calendar.DAY_OF_YEAR, day);
        return timeFormat2.format(calendar.getTime());
    }

    /**
     * 计算一个指定时间延时*时*分后的时间
     * @param startTime 指定时间
     * @param hour  延时小时
     * @param min   延时分钟
     * @return
     */
    public static String getEndTime(String startTime, int hour, int min){
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(timeFormat1.parse(startTime));
            calendar.add(Calendar.HOUR, hour);
            calendar.add(Calendar.MINUTE, min);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return timeFormat1.format(calendar.getTime());
    };

    /**
     * 计算结束日期
     * @param startTime 开始日期
     * @param day   天数
     * @param num   次数
     * @return  返回各次的结束日期
     */
    public static Map<Integer, Object> getEndTimeMap(String startTime, int day, int num) throws ParseException {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(timeFormat2.parse(startTime));
        Map<Integer, Object> map = new HashMap<>();
        for( int i=0; i<num; i++ ){
            if( i==0 ){
                calendar.add(Calendar.DAY_OF_YEAR, day);
            }else{
                calendar.add(Calendar.DAY_OF_YEAR, day);
            }
            String endTime = timeFormat2.format(calendar.getTime());
            map.put(i+1, endTime);
        }
        return map;
    }

    /**
     * 计算结束日期
     * @param startTime 开始日期
     * @param day   天数
     * @param num   次数
     * @return  返回各次的开始结束日期，以逗号隔开
     */
    public static Map<Integer, Object> getTimeRange(String startTime, int day, int num) throws ParseException {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(timeFormat2.parse(startTime));
        Map<Integer, Object> map = new HashMap<>();
        for( int i=0; i<num; i++ ){
            calendar.add(Calendar.DAY_OF_YEAR, day);
            String endTime = timeFormat2.format(calendar.getTime());
            map.put(i+1, startTime+","+endTime);
            calendar.add(Calendar.DAY_OF_YEAR, 1);
            startTime = timeFormat2.format(calendar.getTime());
        }
        return map;
    }

    /**
     * 计算给定时间与当前时间的时间差
     * @param startDate  开始时间，格式：yyyy-MM-dd HH:mm
     * @param endDate    结束时间，格式：yyyy-MM-dd HH:mm
     * @param type      相差时间单位：1-天数，2-小时，3-分钟，4-秒
     *
     * @return
     */
    public static Long getTimeDifference(Date startDate, Date endDate, int type) throws ParseException {
        long nd = 1000 * 24 * 60 * 60;      //每天毫秒数
        long nh = 1000 * 60 * 60;           //每小时毫秒数
        long nm = 1000 * 60;                //每分钟毫秒数
        long ns = 1000;                     //每秒
//        Date startDate = timeFormat4.parse(startTime);
//        Date endDate = timeFormat4.parse(endTime);
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startDate.getTime();
        long timeDiff = 0L;
        if( 1 == type ){
            //计算相差天数
            timeDiff = diff / nd;
        }else if( 2 == type ){
            //计算相差小时
            timeDiff = diff / nh;
        }else if(3 == type ){
            //计算相差多少分钟
            timeDiff = diff / nm;
        }else if(4 == type ){
            //计算相差多少分钟
            timeDiff = diff / ns;
        }else{
            //其他
        }
        return timeDiff;
    }

    /**
     * 查询当前时间的前几天数据
     *
     * @param length
     * @return
     */
    public static String[] getBeforeDay(int length) {
        String[] arr = new String[length];
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = null;
        for (int i = 0; i < arr.length; i++) {
            c = Calendar.getInstance();
            c.add(Calendar.DAY_OF_MONTH, -i - 1);
            arr[(arr.length - 1) - i] = sdf.format(c.getTime());

        }
        return arr;
    }

    /**
     * 查询当前时间的前几天数据
     *
     * @param length
     * @return
     */
    public static String[] getBeforeDayAndNowDay(int length) {
        String[] beforeDay = getBeforeDay(length);
        String[] arr = new String[beforeDay.length + 1];
        Calendar c = null;
        for (int i = 0; i < beforeDay.length; i++) {
            arr[i] = beforeDay[i];
        }
        arr[beforeDay.length] = format2(new Date());
        return arr;
    }

    /**
     * 查询当前时间的前几个数据
     *
     * @param length
     * @return
     */
    public static String[] getBeforeMonth(int length) {
        String[] arr = new String[length];
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Calendar c = null;
        for (int i = 0; i < arr.length; i++) {
            c = Calendar.getInstance();
            c.add(Calendar.MONTH, -i - 1);
            arr[(arr.length - 1) - i] = sdf.format(c.getTime());

        }
        return arr;
    }

    /**
     * 判断当前时间是否在[startTime, endTime]区间，注意时间格式要一致
     *
     * @param nowTime 当前时间
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param format 入参时间的格式
     * @return
     * @author jqlin
     */
    public static boolean isEffectiveDate(String nowTime, String startTime, String endTime, String format) throws ParseException {
        Date nowDate = new SimpleDateFormat(format).parse(nowTime);
        Date startDate = new SimpleDateFormat(format).parse(startTime);
        Date endDate = new SimpleDateFormat(format).parse(endTime);

        if (nowDate.getTime() == startDate.getTime()
                || nowDate.getTime() == endDate.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowDate);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startDate);

        Calendar end = Calendar.getInstance();
        end.setTime(endDate);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }
    /**
          * 获取两个日期之间的所有日期
          * 
          * @param startDate  开始日期
          * @param endDate   结束日期
          * @return  List集合
          */
    public static List<String> getDates(String startDate, String endDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> list = new ArrayList<String>(); //保存日期的集合 
        try {
            Date date_start = sdf.parse(startDate);
            Date date_end = sdf.parse(endDate);
            Date date = date_start;
            Calendar cd = Calendar.getInstance();//用Calendar 进行日期比较判断
            while (date.getTime() <= date_end.getTime()) {
                list.add(sdf.format(date));
                cd.setTime(date);
                cd.add(Calendar.DATE, 1);//增加一天 放入集合
                date = cd.getTime();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String strList = StringUtils.strip(list.toString(), "[]");//去掉符号[]

        System.out.println(list);

        System.out.println(strList);

        return list;
    }

    //返回当前时间yyyy-MM-dd HH:mm:ss
    public static Date getNowDay(){
        return DateUtil.stringtoDate(DateUtil.format1(new Date()),DateUtil.FORMAT_ONE);
    }

    //返回当前时间yyyy-MM-dd
    public static Date getNewDay(Date date){
        return DateUtil.stringtoDate(DateUtil.format2(date),DateUtil.LONG_DATE_FORMAT);
    }

    public static void main(String[] args) throws ParseException {

//        boolean effectiveDateV2 = isEffectiveDate(DateUtil.currDay(), "2020-12-10", "2020-12-13", DateUtil.LONG_DATE_FORMAT);
        System.out.println(JSONObject.toJSONString(getBeforeDayAndNowDay(2)));

    }


}
